package com.lemniscate.audio_and_video_demo.utils;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Created by l on 2018/2/28.
 */

public class AudioTrackUtils {
    private static AudioTrackUtils mInstance;
    private boolean isPlaying;
    private int bufferSize;
    private final AudioTrack audioTrack;
    private DataInputStream dis;

    private AudioTrackUtils() {
        bufferSize = AudioTrack.getMinBufferSize(44100, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
        audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100,
                AudioFormat.CHANNEL_CONFIGURATION_MONO,
                AudioFormat.ENCODING_PCM_16BIT, bufferSize, AudioTrack.MODE_STREAM);

    }

    public static AudioTrackUtils getInstance() {
        if (mInstance == null) {
            synchronized (AudioTrackUtils.class) {
                if (mInstance == null) {
                    mInstance = new AudioTrackUtils();
                }
            }
        }
        return mInstance;
    }

    public void play(String filepath) {
        File file = new File(filepath);
        if (!file.exists()) {
            return;
        }
        try {
            dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        new Thread(new PlayThread()).start();
    }

    public void stop() {
        isPlaying = false;
    }

    private class PlayThread implements Runnable {
        @Override
        public void run() {
            isPlaying = true;

            byte[] buffer = new byte[bufferSize / 4];

            try {
                audioTrack.play();

                while (isPlaying && dis.available() > 0) {
//                    int i = 0;
//                    while (dis.available() > 0 && i < buffer.length) {
//                        buffer[i] = dis.readShort();
//                        i++;
//                    }
                    int read = dis.read(buffer);
                    if (read == AudioTrack.ERROR_INVALID_OPERATION || read == AudioTrack.ERROR_BAD_VALUE) {
                        continue;
                    }

                    audioTrack.write(buffer, 0, read);
                }

                audioTrack.stop();
                dis.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
